package com.yexiao.cofe.business.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson2.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.yexiao.cofe.business.mapper.RoleMapper;
import com.yexiao.cofe.business.mapper.StoreMapper;
import com.yexiao.cofe.business.mapper.UserMapper;
import com.yexiao.cofe.business.mapper.UserRoleMapper;
import com.yexiao.cofe.business.pojo.Role;
import com.yexiao.cofe.business.pojo.Store;
import com.yexiao.cofe.business.pojo.User;
import com.yexiao.cofe.business.pojo.UserRole;
import com.yexiao.cofe.business.service.SmsService;
import com.yexiao.cofe.business.service.UserService;
import com.yexiao.cofe.common.exception.BusinessException;
import com.yexiao.cofe.constant.UserConstant;
import com.yexiao.cofe.util.JwtUtil;
import com.yexiao.cofe.util.SystemUtil;
import com.yexiao.core.util.IDateUtil;
import com.yexiao.core.util.JSONUtil;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

@Service
public class UserServiceImpl implements UserService {

    @Resource
    private UserMapper userMapper;
    @Resource
    private SmsService smsService;
    @Resource
    private RoleMapper roleMapper;
    @Resource
    private StoreMapper storeMapper;
    @Resource
    private UserRoleMapper userRoleMapper;

    @Override
    public JSONObject login(JSONObject param) {
        String phone = JSONUtil.checkAndGetStr(param, "phone");
        Integer verifyCode = JSONUtil.checkAndGetInt(param, "verifyCode");
        String isAdmin = JSONUtil.getStr(param, "isAdmin"); // 是否管理端登录

        // 验证验证码是否正确
        boolean successVerify = smsService.verityCode(phone, verifyCode);
        if (!successVerify) {
            throw new BusinessException("验证失败");
        }

        // 查询账号状态
        User user = userMapper.selectByPhone(phone);
        if(user == null){
            // 账号不存在，创建新账户
            user = createNewUser(phone);
        }

        // 管理端登录, 查找是否为门店人员
        if(StrUtil.isNotEmpty(isAdmin)) {

        }



        return JSONUtil.of("token", JwtUtil.createToken(user));
    }

    /**
     * 创建新用户
     */
    private User createNewUser(String phone) {
        String now = IDateUtil.now();

        User user = new User();
        user.setUserId(generateUserId());
        user.setPhone(phone);
        user.setUserName("默认昵称");
        user.setIsDel(UserConstant.IS_DEL_YES);
        user.setStatus(UserConstant.Status_Running);
        user.setCreateTime(now);
        user.setUpdateTime(now);

        userMapper.insert(user);
        return user;
    }

    /**
     * 生成用户id
     */
    private String generateUserId() {
        return IdUtil.getSnowflakeNextIdStr();
    }

    @Override
    public void exit(String phone) {
        // 删除redis用户token
    }

    @Override
    public void editUserMsg(JSONObject param, String token) {
        User user = getUser(token);
        String avatar = JSONUtil.getStr(param, "avatar");
        String userName = JSONUtil.getStr(param, "userName");

        // 校验
        if(StrUtil.isEmpty(avatar) && StrUtil.isEmpty(userName)) {
            throw new BusinessException("用户信息参数不存在");
        }

        // 设置新值
        if(StrUtil.isNotBlank(avatar)) {
            user.setAvatar(avatar);
        }
        if(StrUtil.isNotBlank(userName)) {
            user.setUserName(userName);
        }

        userMapper.updateById(user);
    }

    @Override
    public JSONObject getCurrentUser(String token) {
        User user = getUser(token);

        return JSONUtil.of(
                "userName", user.getUserName(),
                "userId", user.getUserId(),
                "phone", user.getPhone(),
                "avatar", user.getAvatar(),
                "status", user.getStatus(),
                "createTime", user.getCreateTime(),
                "updateTime", user.getUpdateTime()
        );
    }

    @Override
    public User getUser(String token) {
        String userId = JwtUtil.getUserId(token);
        User user = userMapper.selectByUID(userId);
        if(user == null) {
            throw new BusinessException("用户不存在");
        }

        return user;
    }

    @Override
    public void bindRole(JSONObject param, String token) {
        String storeId = JSONUtil.checkAndGetStr(param, "storeId");
        String userId = JSONUtil.checkAndGetStr(param, "userId");
        List<Integer> roleIdList = JSONUtil.getList(param, Integer.class, "roleIdList");

        User user = userMapper.selectByUID(userId);
        SystemUtil.checkErrorIfNull(user, "用户不存在");
        Store store = storeMapper.selectByStoreId(storeId);
        SystemUtil.checkErrorIfNull(store, "门店不存在");
        List<Role> roleList = listRole(roleIdList);



        // 删除原有角色
        roleMapper.delUserRole(userId);
        List<UserRole> dataList = new ArrayList<>();
        for (Role role : roleList) {
            UserRole userRole = new UserRole();
            userRole.setUserId(userId)
                    .setRoleId(role.getId())
                    .setStoreId(storeId);
            dataList.add(userRole);
        }
        userRoleMapper.insert(dataList);
    }

    @Override
    public List<JSONObject> listRole(JSONObject param, String token) {
        String storeId = JSONUtil.checkAndGetStr(param, "storeId");
        String userId = JSONUtil.checkAndGetStr(param, "userId");

        List<Role> roleList = roleMapper.listRoleByUserIdAndStoreId(userId, storeId);
        List<JSONObject> res = new ArrayList<>();
        for (Role role : roleList) {
            res.add(Role.getBaseMsg(role));
        }
        return res;
    }

    private List<Role> listRole(List<Integer> roleIdList) {
        if(CollectionUtil.isEmpty(roleIdList)) {
            return Collections.emptyList();
        }

        QueryWrapper<Role> wrapper = new QueryWrapper<>();
        wrapper.in(Role.ID, roleIdList);
        return roleMapper.selectList(wrapper);
    }

}
